/**
 * 
 */
package org.wsocket.thread;

import java.nio.channels.SelectionKey;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.wsocket.WSocket;
import org.wsocket.connector.Connector;
import org.wsocket.message.Message;
import org.wsocket.protocol.SocketHandler;

/**
 * ReceiveMessageTask
 * 
 * @author Jeffyd
 */
public class ReceiveMessageTask implements Callable<Boolean> {

	private static Logger log=Logger.getLogger(ReceiveMessageTask.class);
	
	private SelectionKey sk;
	
	private ConcurrentHashMap<String, Connector> connectors;

	public ReceiveMessageTask(SelectionKey sk, ConcurrentHashMap<String, Connector> connectors) {
		this.sk = sk;
		this.connectors = connectors;
	}

	@Override
	public Boolean call() throws Exception {
		String message = SocketHandler.processRequest(sk, connectors);
		if(message != null){
			if(log.isDebugEnabled()){
				log.debug(((Connector) sk.attachment()).getKey() + " send:" + message);
			}
			WSocket.getListener().onMessage(
					new Message((Connector) sk.attachment(), null, message));
		}
		return true;
	}

}
